package com.ybg.engine.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.springframework.jdbc.core.JdbcTemplate;

import com.ybg.util.LogUtil;

public class SimpleMailSenderImpl implements IMailSender{
	MailInfo mailInfo ;
    Properties props = new Properties();
    public SimpleMailSenderImpl(JdbcTemplate jdbcTemplate) {
    	initParam(jdbcTemplate);
    }
    private void initParam(JdbcTemplate jdbcTemplate){
    	mailInfo = MailInfo.getMailInfo(jdbcTemplate);
        props.put("mail.smtp.host", mailInfo.getMailHost()); // 指定SMTP服务器
        props.put("mail.smtp.auth",mailInfo.getMailAuth()); // 指定是否需要SMTP验证
    }
    
	@Override
	public boolean sendMail(String from,String to ,String subject,String content) {
		boolean result = false;
        try {
        	String []  addrArray = to.split(",");
        	InternetAddress[] mailAddress = new InternetAddress [addrArray.length] ;
        	for(int i = 0; i<addrArray.length;i++){
        		mailAddress[i] = new InternetAddress(addrArray[i]);
        	}
            Session mailSession = Session.getDefaultInstance(props);
            Message message = new MimeMessage(mailSession);
            message.setFrom(new InternetAddress(from)); // 发件人
            message.setRecipients(Message.RecipientType.TO, mailAddress); // 收件人
            subject = MimeUtility.encodeWord(subject, "UTF-8", "B");
            message.setSubject(subject); // 邮件主题
            
            // 设置正文为混合模式
        	MimeMultipart mime = new MimeMultipart("mixed");
    		MimeBodyPart body = new MimeBodyPart();
    		body.setContent(content, "text/html; charset=UTF-8");
    		mime.addBodyPart(body);
    		message.setContent(mime);
    		
//            message.setDataHandler(new DataHandler(
//            		new ByteArrayDataSource(content, "text/html;charset=UTF-8")));
            
            message.saveChanges();
            Transport transport = mailSession.getTransport(mailInfo.getMailProtocol());
            transport.connect(mailInfo.getMailHost(), mailInfo.getMailAccount(), mailInfo.getMailPassword());
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            result = true;
            
        } catch(Exception ex){
        	LogUtil.error("发送邮件失败",ex);
        }
		return result;
	}
}